﻿using Microsoft.AspNetCore.Mvc;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Model.Input;
using Wechat_PublicNumber.Model.Output;
using Wechat_PublicNumber.Repository;

namespace Wechat_PublicNumber.Controllers
{
    [Route("User")]
    [ApiController]
    public class UserController : BasicController
    {

        #region DI
        [Autowired]
        private UserRepository _userRepository;
        #endregion

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<UserInfoOutput> GetUserInfo()
        {
            try
            {
                var user = await _userRepository.GetUserInfo(UserInfo.ID);
                if (user is not null)
                    return new UserInfoOutput() { WeChatNickName = user.NickName, WeChatHeadImgUrl = user.Headimgurl };
                throw new OutPutException("该用户无效");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetUserInfo Error");
                throw;
            }
        }

        /// <summary>
        /// 获取微信模板列表
        /// </summary>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        [HttpGet("WxTemplate")]
        public async Task<List<PushTemplateListOutput>> GetPushTemplateList([FromQuery] string KeyWord)
        {
            try
            {
                return await _userRepository.GetPushTemplateList(KeyWord, UserInfo.OpenID);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetPushTemplateList Error");
                throw;
            }
        }

        /// <summary>
        /// 更新模板状态
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpPut("WxTemplate/Status/{ID}")]
        public async Task<bool> UpdateWxTemplateStatus([FromRoute] WeChatTemplateEnum ID)
        {
            try
            {
                var nowTime = DateTime.Now;
                var tempData = await _userRepository.GetWeChatTemplateSet(ID, UserInfo.OpenID);
                if (tempData is null)
                    tempData = new WeChatTemplateSet()
                    {
                        OpenID = UserInfo.OpenID,
                        TemplateID = ID,
                        Status = false,
                        CreateTime = nowTime
                    };
                else
                {
                    tempData.Status = !tempData.Status;
                    tempData.UpdateTime = nowTime;
                }

                await _userRepository.SaveWeChatTemplateSet(tempData);

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "UpdateWxTemplateStatus Error");
                throw;
            }
        }
    }
}
